// pages/address/address.js
import request from '../../utils/request'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    addressBookList: [],
    type: ""
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.setData({
      type: options.type
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  async onShow() {
    const {
      result
    } = await request({
      url: '/user/addressBook/list'
    })
    // console.log(result);
    this.setData({
      addressBookList: result
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },
  toAddOrEditAddress() {
    wx.navigateTo({
      url: '/pages/addOrEditAddress/addOrEditAddress',
    })
  },
  async onChangeCheckbox(e) {
    // console.log(e.currentTarget.dataset.id);
    await request({
      method: "patch",
      url: `/user/addressBook/setDefault/${e.currentTarget.dataset.id}`
    })
    const {
      result
    } = await request({
      url: '/user/addressBook/list'
    })
    // console.log(result);
    this.setData({
      addressBookList: result
    })
  },
  onEditAddress(e) {
    // console.log(e);
    const addressId = e.currentTarget.dataset.id;
    const {
      type
    } = this.data
    if (!type) {
      wx.navigateTo({
        url: `/pages/addOrEditAddress/addOrEditAddress?id=${e.currentTarget.dataset.id}&type=1`,
      })
    } else {
      const pages = getCurrentPages()
      // console.log(pages);
      const orderPage=pages[pages.length-2]
      if(orderPage){
        orderPage.getAddressId(addressId,()=>{
          wx.navigateBack();
        })
      }
      
    }

  },
  // 删除地址
  onDeleteAddress(e) {
    const addressId = e.currentTarget.dataset.id;
    wx.showModal({
      title: '确认删除',
      content: '确认要删除该地址吗?',
      confirmColor: '#f4333c',
      success: async (res) => {
        if (res.confirm) {
          await request({
            url: `/user/addressBook/delete/${addressId}`,
            method: "delete"
          })
          wx.showToast({
            title: '删除成功',
            icon: 'success',
            duration: 1500
          });
          const {
            result
          } = await request({
            url: '/user/addressBook/list'
          })
          // console.log(result);
          this.setData({
            addressBookList: result
          })
        }
      }
    })
  }
})